<?php

declare(strict_types=1);

namespace App\Amqp\Consumer;

use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use PhpAmqpLib\Message\AMQPMessage;
use Hyperf\Amqp\Message\Type;
use Hyperf\Amqp\Result;
use Service\CommodityService\CommodityStockSkillService;
use Service\Code\Normal;

/**
 * qos (prefetch_size,prefetch_count,global)
 * 库存扣减服务
 * @Consumer(exchange="STOCK_REDIS_SERVICE", routingKey="STOCK_REDIS_SERVICE", queue="STOCK_REDIS_SERVICE", nums=1)
 */
class StockRedisServiceMessageConsumer extends ConsumerMessage
{
    protected $type = Type::DIRECT;//直连模式
    protected $qos  = [
        'prefetch_count'    => 10
    ];
    public function consumeMessage($data, AMQPMessage $message): string
    {
        try 
        {
            $result = CommodityStockSkillService::instance()->syncMysqlStockDecr($data['skuCode'],$data['number']);
            if( $result['code'] != Normal::SUC ) {
                sleep(3);//休眠3秒之后，重回队列
                return Result::REQUEUE;
            }
            
            return Result::ACK;
        } 
        catch ( \Throwable $t ) 
        {
            sleep(3);//休眠3秒之后，重回队列
            return Result::REQUEUE;
        }
    }
    
    /**
     * 设置是否自启动
     */
    public function isEnable() : bool
    {
        $isEnable = env('AMQP_STOCK_REDIS_SERVICE_MESSAGE_CONSUMER_ENABLE');
        return $isEnable ? true : false ;
    }
}